<template>
  <el-form
    ref="formRef"
    :model="dynamicValidateForm"
    label-width="auto"
    class="demo-dynamic"
  >
    <el-form-item
      prop="title"
      label="下投名目"
      :rules="[
        {
          required: true,
          message: '请输入下投名目',
          trigger: 'blur',
        }
      ]"
    >
      <el-input v-model="dynamicValidateForm.title" />
    </el-form-item>
    <el-form-item
      class=".inline-content"
      v-for="(unit, index) in dynamicValidateForm.units"
      :key="unit.id"
      :label="'工装' + (index+1)"
      :prop="'units.' + index + '.count'"
      :rules="[{
        required: true,
        message: 'unit can not be null',
        trigger: 'blur',
      },{
        type:'number',
        message:'必须是一个整数',
        trigger:['blur','change']
      },{
          validator: (rule, value, callback) => {
            if (value < 1) {
              callback(new Error('至少投一个'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }]"
    >

    <el-select v-model="unit.id" placeholder="Select"  
          style="width: 300px;">
      <el-option
        v-for="item in options"
        :key="item._id"
        :label="`${item.drawingNo}-${item.name}-${item.code}`"
        :value="item.code"
        :disabled="item.disabled"
        
      />
    </el-select>
  
       数量：<el-input  v-model.number="unit.count" 
          style="width: 300px;"/>
      <el-button class="mt-2" @click.prevent="removeunit(unit)">
        Delete
      </el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)">Submit</el-button>
      <el-button @click="addunit">New unit</el-button>
      <el-button @click="resetForm(formRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'

import type { FormInstance } from 'element-plus'

const options = await $fetch('/api/hejia',{method:'GET'})

const formRef = ref<FormInstance>()
const dynamicValidateForm = reactive<{
  units: unitItem[]
  title: string
}>({
  units: [
    {
      count: 1,
      id:''
    },
  ],
  title: '',
})

interface unitItem {
  id:string
  count: number
}

const removeunit = (item: unitItem) => {
  const index = dynamicValidateForm.units.indexOf(item)
  if (index !== -1) {
    dynamicValidateForm.units.splice(index, 1)
  }
}

const getPurchaseId = async ()=>{
   const datas = await $fetch('/api/purchase',{method:'get'})
   let index = 0;
   datas.forEach((data)=>{
    console.log("遍历",data)
    const id = Number(data.id.split('-')[1])
      if(index<id){
        index = id
      }
   })

   return `J/GZT25-${index+1}`
}

const addunit = () => {
  dynamicValidateForm.units.push({
    count: 1,
    id:''
  })
}

// 1. 定义处理函数
function timestampToDate(timestamp) {
  // 时间戳可能是毫秒（13位）或秒（10位），先统一转为毫秒
  const date = new Date(timestamp.toString().length === 10 ? timestamp * 1000 : timestamp);
  
  // 获取年、月、日（月从0开始，需+1）
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零（如9→09）
  const day = String(date.getDate()).padStart(2, '0'); // 补零（如5→05）
  
  // 拼接格式
  return `${year}/${month}/${day}`;
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async(valid) => {
    if (valid) {
      dynamicValidateForm.date =timestampToDate(Date.now())
      dynamicValidateForm.id= await getPurchaseId()
      await $fetch('/api/purchase',{
        method:'post',
        body:dynamicValidateForm
      })
      emit('submit')
    } else {
      console.log('error submit!')
    }
  })
}

const emit = defineEmits(['submit'])

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style lang="css" scoped>
/* 关键样式：让内容横向排列 */
.inline-content {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 元素之间的间距 */
  width: 100%; /* 占满表单项宽度 */
}
</style>